package com.healthy.intercepter;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.healthy.entity.YgAdmins;
import com.healthy.util.PowerUtil;

public class DAdminCharpter implements HandlerInterceptor{

	/**
	 * 拦截一些请求，只有管理员符合权限才能使用该接口
	 */
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 修正拦截器返回给客户端的信息编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        int statusCode = -3;
        String msg = "你没有足够的权限执行该操作";
        JSONObject json = new JSONObject();
        // 验证角色的权限
        Object role = request.getSession().getAttribute("role");  // role=user/admin
        Object u = null;
        if("admin".equals( (String)role) ){
        	u = request.getSession().getAttribute("admin");
        	YgAdmins admin = (YgAdmins)u;
        	Integer powerValue = admin.getPowerValue();
        	boolean canUse = PowerUtil.haveManageCharpter(powerValue);
        	if(canUse){
        		/*该用户拥有修改文章权限*/
        		return true;
        	}
        }else if("user".equals( (String)role) ){
        	// 普通用户不需考虑，该权限只属于管理员
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.write(json.toJSONString());
        pw.flush();
        pw.close();
        return false;
    }

	/**
	 * 当preHandle返回true，请求才能到达指定处理器适配器HandlerAdapter
	 */
	
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    
    /**
     * 无论preHandle是否放行请求该方法都会执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
